/**   
 *    
 * 项目名称：SmartKungFu   
 * 类名称：GymnasiumDetailController   
 * 类描述：场馆详情控制类   
 * 创建人：zhangl  
 * 创建时间：2016年10月21日 下午12:38:01   
 * 修改人：zhangl   
 * 修改时间：2016年10月21日 下午12:38:01   
 * 修改备注：   
 * @version    
 *    
 */
package com.lst.controller;

import java.text.ParseException;
import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.validation.Valid;

import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.validation.BindingResult;
import org.springframework.validation.ObjectError;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.servlet.ModelAndView;

import com.github.miemiedev.mybatis.paginator.domain.PageBounds;
import com.github.miemiedev.mybatis.paginator.domain.PageList;
import com.github.miemiedev.mybatis.paginator.domain.Paginator;
import com.lst.common.BaseController;
import com.lst.common.CommonEnum;
import com.lst.exception.MyException;
import com.lst.model.CoursePackage;
import com.lst.model.FolPara;
import com.lst.model.GymnasiumDetail;
import com.lst.model.MstButton;
import com.lst.model.MstRoll;
import com.lst.model.MstUser;
import com.lst.model.Resources;
import com.lst.service.CoursePackageService;
import com.lst.service.GymnasiumDetailService;
import com.lst.service.MstButtonService;
import com.lst.service.MstRollService;
import com.lst.service.ResourcesService;
import com.lst.utils.CommonUtils;
import com.lst.utils.DateUtil;

/**
 * @ClassName: GymnasiumDetailController
 * @Description: 场馆详情控制类
 * @author zhangl
 * @date 2016年10月21日 下午12:38:01
 *
 */
@Controller
@RequestMapping("gymnasiumDetailController")
public class GymnasiumDetailController extends BaseController {

	@Autowired
	private GymnasiumDetailService gymnasiumDetailService;

	@Autowired
	private MstButtonService mstButtonService;

	@Autowired
	private ResourcesService resourcesService;

	@Autowired
	private CoursePackageService coursePackageService;

	@Autowired
	private MstRollService mstRollService;

	/**
	 * 
	 * @Title: list
	 * @Description:  页面加载
	 * @param @param menuId
	 * @param @param page
	 * @param @param rows
	 * @param @param index_exp
	 * @param @param index_che
	 * @param @param minDate
	 * @param @param maxDate
	 * @param @param gymName
	 * @param @return
	 * @param @throws MyException    设定文件
	 * @return ModelAndView    返回类型
	 */
	@RequestMapping(value = "/list")
	public ModelAndView list(
			@RequestParam(required = true) int menuId,
			@RequestParam(required = false,defaultValue = CommonEnum.SYSTEMPAGE_PAGE) int page,
			@RequestParam(required = false,defaultValue = CommonEnum.SYSTEMPAGE_PAGESIZE) int rows,
			@RequestParam(required = false,defaultValue = CommonEnum.MENU_STYLE_INDEX_EXP) String index_exp,
			@RequestParam(required = false,defaultValue = CommonEnum.MENU_STYLE_INDEX_CHE) String index_che,
			@RequestParam(required = false,defaultValue = "") String minDate,
			@RequestParam(required = false,defaultValue = "") String maxDate,
			@RequestParam(required = false,defaultValue = "") String gymName) throws MyException {
		Date startDate = new Date();
		logger.info("list begin: " + startDate);

		FolPara folPara = new FolPara();
		folPara.setMenuId(menuId);
		folPara.setPage(page);
		folPara.setRows(rows);
		folPara.setGymName(gymName);

		folPara.setMinDate(minDate);
		folPara.setMaxDate(maxDate);

		MstUser mstUser = this.getMySession().getMstUser();
		List<MstButton> btns = CommonUtils.readPermissionWithBtn(menuId, mstUser, mstButtonService);

		ModelAndView mv = new ModelAndView(CommonEnum.FORWARD_VIEW_MAIN_KUNGFU + "gd_list");
		mv.addObject("btns", btns);
		mv.addObject("folPara",folPara);

		mv.addObject("MENU_STYLE_INDEX_EXP", index_exp);
		mv.addObject("MENU_STYLE_INDEX_CHE", index_che);

		logger.info("list end run(s): " + DateUtil.calLastedTime(startDate));

		return mv;
	}

	/**
	 * 
	 * @Title: queryList
	 * @Description:数据加载
	 * @param @param page
	 * @param @param pageSize
	 * @param @param sort
	 * @param @param order
	 * @param @param minDate
	 * @param @param maxDate
	 * @param @param gymName
	 * @param @return
	 * @param @throws MyException    设定文件
	 * @return Object    返回类型
	 */
	@RequestMapping(value = "/queryList")
	@ResponseBody
	public Object queryList(
			@RequestParam(required = false,defaultValue = CommonEnum.SYSTEMPAGE_PAGE) Integer page,
			@RequestParam(required = false,defaultValue = CommonEnum.SYSTEMPAGE_PAGESIZE) Integer pageSize,
			@RequestParam(required = false,defaultValue = "")String sort,
			@RequestParam(required = false,defaultValue = CommonEnum.SYSTEM_ORDER_DESC)String order,
			@RequestParam(required = false,defaultValue = "") String minDate,
			@RequestParam(required = false,defaultValue = "") String maxDate,
			@RequestParam(required = false,defaultValue = "")String gymName) throws MyException {
		Date startDate = new Date();
		logger.info("queryList begin: " + startDate);

		Map<String, Object> reqMap = new HashMap<String,Object>();
		reqMap.put("isDeleted", 0);
		reqMap.put("enabled", 1);

		if(StringUtils.isEmpty(sort)){
			reqMap.put("orderByClause","gd.createdate desc");
		} else{
			reqMap.put("orderByClause",sort + " " + order);
		}

		if(!StringUtils.isBlank(gymName)){
			reqMap.put("_gymName", gymName.trim());
		}

		if(!StringUtils.isBlank(minDate) && !StringUtils.isBlank(maxDate)){
			try {
				if(DateUtil.parse(minDate).after(DateUtil.parse(maxDate))){
					reqMap.put("minDate", maxDate + DateUtil.START_DATE_HMS);
					reqMap.put("maxDate", minDate + DateUtil.END_DATE_HMS) ;
				}else{
					reqMap.put("minDate", minDate + DateUtil.START_DATE_HMS);
					reqMap.put("maxDate", maxDate + DateUtil.END_DATE_HMS);
				}
			} catch (ParseException e) {
				logger.error("queryList error: " ,e);
			}
		}	

		PageBounds pageBounds = new PageBounds(page, pageSize);
		List<GymnasiumDetail> list = gymnasiumDetailService.queryListByMap(reqMap, pageBounds);

		pageBounds = new PageBounds();
		List<CoursePackage> cps = new ArrayList<>();
		List<MstRoll> rolls = new ArrayList<>();

		for (GymnasiumDetail gd : list) {
			//查询优惠券
			reqMap.clear();
			reqMap.put("enabled", true);
			reqMap.put("isDeleted", false);
			reqMap.put("type", CommonEnum.SYSCODE_YHQ_TYPE_KC); //优惠券类型 ： 课程			
			reqMap.put("resourceId", gd.getId());
			reqMap.put("orderByClause","r.createdate desc");
			rolls = mstRollService.queryByList(reqMap, pageBounds);
			gd.setRolls(rolls);

			//查询套餐
			reqMap.clear();
			reqMap.put("enabled", true);
			reqMap.put("isDeleted", false);
			reqMap.put("courseId",gd.getId());
			reqMap.put("orderByClause", "cp.createdate");
			cps =  coursePackageService.queryByList(reqMap, pageBounds);
			gd.setCps(cps);
		}

		PageList<GymnasiumDetail> pageList = (PageList<GymnasiumDetail>) list;
		Paginator paginator = pageList.getPaginator();

		HashMap<String, Object> indexPages = new HashMap<String, Object>();
		indexPages.put("total", paginator.getTotalCount());	
		indexPages.put("rows", list);

		logger.info("queryList end run(s): " + DateUtil.calLastedTime(startDate));

		return indexPages;
	}

	/**
	 * 
	 * @Title: edit
	 * @Description: edit
	 * @param @param id
	 * @param @return    设定文件
	 * @return ModelAndView    返回类型
	 */
	@RequestMapping(value = "/edit")
	public ModelAndView edit(
			@RequestParam(required = false) String id,
			@RequestParam(required = false,defaultValue = CommonEnum.MENU_STYLE_INDEX_EXP) String index_exp,
			@RequestParam(required = false,defaultValue = CommonEnum.MENU_STYLE_INDEX_CHE) String index_che) {
		Date startDate = new Date();
		logger.info("edit begin: " + startDate);

		ModelAndView mv = new ModelAndView(CommonEnum.FORWARD_VIEW_MAIN_KUNGFU + "gd_edit");

		if (!StringUtils.isBlank(id)) {
			GymnasiumDetail gd = gymnasiumDetailService.selectByPrimaryKey(Integer.parseInt(id));
			mv.addObject("gd", gd);
		}

		mv.addObject("MENU_STYLE_INDEX_EXP", index_exp);
		mv.addObject("MENU_STYLE_INDEX_CHE", index_che);

		logger.info("edit end run(s): " + DateUtil.calLastedTime(startDate));

		return mv;
	}

	/**
	 * 
	 * @Title: save
	 * @Description: 保存
	 * @param @param gymnasiumDetail
	 * @param @param br
	 * @param @param folPara
	 * @param @param imagename
	 * @param @param request
	 * @param @return
	 * @param @throws MyException    设定文件
	 * @return String    返回类型
	 */
	@RequestMapping(value = "/save",method = RequestMethod.POST)
	public String save(@Valid GymnasiumDetail gymnasiumDetail,BindingResult br,
			FolPara folPara, String [] imagename,
			HttpServletRequest request) throws MyException {
		Date startDate = new Date();
		logger.info("save begin: " + startDate);

		MstUser mstUser = this.getMySession().getMstUser();

		//拦截非法请求参数
		try {
			if (br.hasErrors()){
				List<ObjectError> ers = br.getAllErrors();
				logger.info("--------------form parameter error start-----------------------");

				for(ObjectError er : ers){
					logger.info("save faile with parameter illegal: " + er.getDefaultMessage() );
				}

				logger.info("--------------form parameter error end-----------------------");
			} else {
				if (gymnasiumDetail.getId() != null) {
					gymnasiumDetail.setUpdatedate(startDate);
					gymnasiumDetail.setUpdateuser(mstUser.getId());

					gymnasiumDetailService.updateByPrimaryKeySelective(gymnasiumDetail);
				} else {
					gymnasiumDetail.setEnabled(true);
					gymnasiumDetail.setIsdeleted(false);
					gymnasiumDetail.setCreatedate(startDate);
					gymnasiumDetail.setUpdatedate(startDate);
					gymnasiumDetail.setCreateuser(mstUser.getId());

					gymnasiumDetailService.insert(gymnasiumDetail);
				}

				//图片资源信息维护
				if(imagename != null && imagename.length != 0){
					Map<String, String> resMap = new HashMap<String,String>();
					resMap.put("userId", mstUser.getId().toString());
					resMap.put("ownerId", gymnasiumDetail.getId().toString());
					resMap.put("tableName", "GYMNASIUM_DETAIL");

					Map<String, Object> dataMap = CommonUtils.getResourcesData(request, imagename, resMap,CommonEnum.SYSCODE_REOURCES_TYPE_IMAGE,true);

					@SuppressWarnings("unchecked")
					List<Resources> resources = (List<Resources>) dataMap.get("resources");
					String reserved12 = (String) dataMap.get("zipFile");
					
					resourcesService.saveList(resources);

					String imagePath = resources.get(0).getRespath() + resources.get(0).getResname();

					GymnasiumDetail imgGd = new GymnasiumDetail();
					imgGd.setUpdatedate(startDate);
					imgGd.setUpdateuser(mstUser.getId());
					imgGd.setId(gymnasiumDetail.getId());
					imgGd.setCoursebill(imagePath);
					imgGd.setReserved12(reserved12);
					
					gymnasiumDetailService.updateByPrimaryKeySelective(imgGd);
				}

			}
		} catch (Exception e) {
			logger.error("save error: " ,e);
		}

		StringBuffer sb = new StringBuffer("?");
		sb.append("menuId=" + folPara.getMenuId());
		sb.append("&page=" + folPara.getPage());
		sb.append("&pageSize=" + folPara.getPageSize());
		sb.append("&gymName=" + folPara.getGymName());
		
		sb.append("&minDate=" + folPara.getMinDate());
		sb.append("&maxDate=" + folPara.getMaxDate());
		
		sb.append("&index_exp=" + folPara.getIndex_exp());
		sb.append("&index_che=" + folPara.getIndex_che());

		logger.info("save end run(s):" + DateUtil.calLastedTime(startDate));

		return "redirect:list" + sb.toString();
	}

	/**
	 * 
	 * @Title: isUnique
	 * @Description: 验证属性唯一性
	 * @param @param property 
	 * @param @param id
	 * @param @return    设定文件
	 * @return Boolean    返回类型
	 */
	@RequestMapping(value = "/isUnique",method = RequestMethod.GET)
	@ResponseBody
	public Boolean isUnique(
			@RequestParam(required = true)String property,
			@RequestParam(required = false,defaultValue = "")String id){
		Date startDate = new Date();
		logger.info("isUnique begin: " + startDate);

		boolean flag = false;

		Map<String, Object> reqMap = new HashMap<String,Object>();
		reqMap.put("enabled", 1);
		reqMap.put("isDeleted", 0);
		reqMap.put("rolNo", property);

		List<GymnasiumDetail> gds = gymnasiumDetailService.queryByList(reqMap, new PageBounds());

		if(gds.isEmpty()) flag = true;

		else{
			if(!StringUtils.isBlank(id)){//当为编辑操作时，存在唯一一个相同的名称名，验证通过
				if(gds.get(0).getId().equals(Integer.valueOf(id))){
					flag = true;
				}
			}
		}

		logger.info("isUnique end run(s): " 
				+ DateUtil.calLastedTime(startDate));

		return flag;
	}


	/**
	 * 
	 * @Title: delList
	 * @Description: 批量删除
	 * @param @param request
	 * @param @param response
	 * @param @param ids
	 * @param @return
	 * @param @throws MyException    设定文件
	 * @return boolean    返回类型
	 */
	@RequestMapping("delList")
	@ResponseBody
	public boolean delList(HttpServletRequest request, HttpServletResponse response,
			@RequestParam(required = true) String ids) throws MyException {
		Date startDate = new Date();
		logger.info("delList begin: " + startDate);

		boolean flag = false;

		MstUser mstUser = this.getMySession().getMstUser();

		Map<String, Object> reqMap = new HashMap<String,Object>();
		reqMap.put("ids", ids);
		reqMap.put("updateUser", mstUser.getId());

		try {
			gymnasiumDetailService.delList(reqMap);
			flag = true;
		} catch (Exception e) {
			logger.error("delList error: " ,e);
		}

		logger.info("delList end run(s): " + DateUtil.calLastedTime(startDate));

		return flag;
	}
}
